//
//  YSShareManager.m
//  newYueLvHui
//
//  Created by Apple on 2020/9/12.
//  Copyright © 2020 Facebook. All rights reserved.
//

#import "YSShareManager.h"
#import "YSShareVew.h"
#import "WXApi.h"
#import <Photos/Photos.h>

@implementation YSShareManager

- (void)sharePlatforms:(NSArray *)platforms layoutColumn:(NSInteger)column layoutRow:(NSInteger)row  shareMessageModel:(YSShareMessageModel *)shareData {
    
    [self sharePlatforms:platforms layoutColumn:column layoutRow:row shareMessageModel:shareData shareViewTitle:nil];
}

- (void)sharePlatforms:(NSArray *)platforms layoutColumn:(NSInteger)column layoutRow:(NSInteger)row  shareMessageModel:(YSShareMessageModel *)shareData shareViewTitle:(NSAttributedString * __nullable)attrString
{
    YSShareVew *shareView = [[YSShareVew alloc] initWithColumn:column row:row platforms:platforms customConfig:self.customConfig];
    shareView.attrString = attrString;
    [shareView showSharePlatformView];
    shareView.sharePlatformBlock = ^(YSSharePlatformType type) {
        [self shareToPlatform:type messageModel:shareData];
    };
    shareView.savePhotoBlock = ^(UIImage * _Nonnull image) {
        [self savePhotoWithImage:image];
    };

}

#pragma mark---分享平台点击事件
- (void)shareToPlatform:(YSSharePlatformType)type messageModel:(YSShareMessageModel *)shareData
{
    switch (type) {
        case YS_WXSession:
            
            [self shareToWXPlatformWithData:shareData platformType:YS_WXSession];
            
            break;
        case YS_WXTimeline:
            
            [self shareToWXPlatformWithData:shareData platformType:YS_WXTimeline];
            
            break;
        case YS_WXMinProgram:
            
            if (self.shareMinProgramActionBlock) {
                self.shareMinProgramActionBlock(self);
                return;
            }

            break;
        case YS_CopyLink:
            
            if (self.copyLinkActionBlock) {
                self.copyLinkActionBlock(self);
                return;
            }
            [self copyLinkWithData:shareData];
            
            break;
        case YS_Placard:
           
            if (self.createPlacardActionBlock) {
                self.createPlacardActionBlock(self);
                return;
            }
           
            break;
        case YS_Other:
            
            if (self.customActionBlock) {
                self.customActionBlock(self);
            }
        default:
            break;
    }
}

#pragma mark---分享到微信平台
- (void)shareToWXPlatformWithData:(YSShareMessageModel *)shareModel platformType:(YSSharePlatformType)platformType
{
 
    if ([WXApi isWXAppInstalled] == NO) {
        [self showHint:@"您没有安装微信" afterDelay:2.0];
        return;
    }
    
    if ([shareModel isKindOfClass:YSShareImageModel.class] ) {
        YSShareImageModel *model = (YSShareImageModel *)shareModel;
        [self shareImageToWXWithData:model platformType:platformType];
    }else if ([shareModel isKindOfClass:YSShareWebLinkModel.class]){
        YSShareWebLinkModel *model = (YSShareWebLinkModel *)shareModel;
        [self shareWebLinkToWXWithData:model platformType:platformType];
    }else{
        [self showHint:@"暂不支持此平台分享" afterDelay:2.0];
    }
}

#pragma mark---分享图片
- (void)shareImageToWXWithData:(YSShareImageModel *)shareModel platformType:(YSSharePlatformType)platformType
{
    WXImageObject *imageObject = [WXImageObject object];
    imageObject.imageData = shareModel.imageData;

    WXMediaMessage *message = [WXMediaMessage message];
    message.mediaObject = imageObject;

    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    if (platformType == YS_WXSession) {
         req.scene = WXSceneSession;
    }else if (platformType == YS_WXTimeline){
        req.scene = WXSceneTimeline;
    }
    [WXApi sendReq:req completion:^(BOOL success) {
        if (!success) {
            [self showHint:@"打开微信失败" afterDelay:2.0];
        }
    }];
    
}

- (void)showHint:(NSString *)hint afterDelay:(CGFloat)afterDelay {
    
    if (hint && [hint isKindOfClass:[NSString class]] && hint.length >0) {
        
        MBProgressHUD *hud  = [[MBProgressHUD alloc] init];
        [[[UIApplication sharedApplication].delegate window] addSubview:hud];
        hud.mode = MBProgressHUDModeCustomView;
        hud.removeFromSuperViewOnHide = YES;
        if (hint != nil && hint.length > 0) {
            hud.label.font = [UIFont font_systemRegularFontWithSize:15];
            hud.label.text = hint;
        }
        [hud showAnimated:YES];
        [hud hideAnimated:YES afterDelay:afterDelay];
    }
}

#pragma mark---分享网页链接
- (void)shareWebLinkToWXWithData:(YSShareWebLinkModel *)shareModel platformType:(YSSharePlatformType)platformType
{
    WXWebpageObject *webpageObject = [WXWebpageObject object];
    webpageObject.webpageUrl = shareModel.webpageUrl;
   
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = shareModel.title;
    message.description = shareModel.desc;
    [message setThumbImage:shareModel.thumbImage];
    message.mediaObject = webpageObject;
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    if (platformType == YS_WXSession) {
        req.scene = WXSceneSession;
    }else if (platformType == YS_WXTimeline){
        req.scene = WXSceneTimeline;
    }
    [WXApi sendReq:req completion:^(BOOL success) {
        if (!success) {
            [self showHint:@"打开微信失败" afterDelay:2.0];
        }
    }];
}

#pragma mark---分享小程序
- (void)shareMinProgramToWXWithData:(YSShareMinProgramModel *)shareModel
{
    WXMiniProgramObject *object = [WXMiniProgramObject object];
    object.webpageUrl = shareModel.webpageUrl;
    object.userName = shareModel.userName;
    object.path = shareModel.path;
    object.hdImageData = shareModel.hdImageData;
    object.withShareTicket = shareModel.withShareTicket;
    object.miniProgramType = (WXMiniProgramType) shareModel.miniprogramType;
    
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = shareModel.title;
    message.description = shareModel.desc;
    message.thumbData = nil;  //兼容旧版本节点的图片，小于32KB，新版本优先
    message.mediaObject = object;
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = WXSceneSession;  //目前只支持会话
    [WXApi sendReq:req completion:^(BOOL success) {
        if (!success) {
            [self showHint:@"打开微信失败" afterDelay:2.0];
        }
    }];
    
}

#pragma mark---复制链接
- (void)copyLinkWithData:(YSShareMessageModel *)shareModel
{
    if (shareModel.copyed_link.length == 0) {
        return;
    }
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = shareModel.copyed_link;
    [self showHint:@"复制成功" afterDelay:2.0];
}

#pragma mark---生成海报
- (void)createPlacardWithData:(YSShareImageModel *)shareModel
{
    YSShareVew *shareView = [[YSShareVew alloc] initWithColumn:3 row:1 platforms:@[@(YS_WXSession),@(YS_WXTimeline),@(YS_SavePhoto)]];
    [shareView showPlacardView];
    if (shareModel.placard_url) {
        shareView.placard_url = shareModel.placard_url;
    }
    if (shareModel.placardImage) {
        shareView.placardImage = shareModel.placardImage;
    }
    shareView.sharePlacardBlock = ^(YSSharePlatformType type, UIImage * _Nonnull image) {
        //此处分享应该是图片类型
        if ([shareModel isKindOfClass:YSShareImageModel.class]) {
            shareModel.imageData = UIImagePNGRepresentation(image ?: shareModel.placardImage);
            [self shareToPlatform:type messageModel:shareModel];
        }else{
            
        }
    };
    
    //保存相册
    shareView.savePhotoBlock = ^(UIImage * _Nonnull image) {
        [self savePhotoWithImage:image];
    };
}


#pragma mark---保存相册
- (void)savePhotoWithImage:(UIImage *)image
{
    if (image == nil) {
        return;
    }
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if (status == PHAuthorizationStatusAuthorized) {
            //允许使用相册
            UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        }else{
            //不允许使用相册，此处应该弹出设置提示框，可以跳转到设置相册权限界面，暂时只是提示一下
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showHint:@"无权访问相册功能，请在设置中启用" afterDelay:1.5];
            });
        }
    }];

}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error  contextInfo:(void *)contextInfo
{
    if (error) {
        [self showHint:@"保存失败" afterDelay:1.5];
    } else {
        if (self.saveCompletionActionBlock) {
            self.saveCompletionActionBlock(self);
            return;
        }
        [self showHint:@"保存成功" afterDelay:1.5];
    }
}

- (void)dealloc
{
     NSLog(@"%@已释放",NSStringFromClass(self.class));
}


@end
